package com.schooleducation.controller.teacher;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.schooleducation.entity.Lesson;
import com.schooleducation.entity.User;
import com.schooleducation.service.ServiceFactory;
import com.schooleducation.uitls.DateJsonValueProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("/teacher/studentInfo")
public class StudentInfoController {

	@Resource(name = "serviceFac")
	private ServiceFactory serviceFac;

	@RequestMapping(method = RequestMethod.GET)
	public String getPage(Model model, HttpSession session) {
		User teacher = (User) session.getAttribute("teacher");
		if (teacher != null) {
			List<Lesson> list = serviceFac.getLessonService().getLessonListByTeacher(teacher);
			model.addAttribute("teacher", teacher);
			model.addAttribute("lessonList", list);
			model.addAttribute("studentList", serviceFac.getUserService().getUserListByLesson(list.get(0)));

			return "teacher/studentInfo";
		} else {
			return "redirect:../login";
		}

	}

	@RequestMapping(method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getStudentList(Integer lessonId) {

		Lesson lesson = new Lesson();
		lesson.setId(lessonId);
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[] { "lesson", "userPassword", "userRoles", "userInfo" });
		config.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor());

		return JSONArray.fromObject(serviceFac.getUserService().getUserListByLesson(lesson), config).toString();
	}

	@RequestMapping(value = "audit", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String auditStudent(HttpSession session, int subscribeId, int state) {
		Map<String, Object> statePut = new HashMap<String, Object>();
		User teacher = (User) session.getAttribute("teacher");
		if (teacher != null) {
			statePut.put("isLogin", "yes");
			if (serviceFac.getUserService().auditStudent(subscribeId, state)) {
				statePut.put("update", "success");
			} else {
				statePut.put("update", "fail");
			}
		} else {
			statePut.put("isLogin", "no");
		}
		return JSONObject.fromObject(statePut).toString();
	}
}
